package com.cxb.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.cxb.entity.GpsDestinationInfo;
import com.cxb.entity.SMS;
import com.cxb.manager.PhoneManager.PhoneState;
import com.cxb.utils.CommonUtils;
import com.cxb.utils.Constants;
import com.cxb.utils.DBHelp;

/**
 * @ClassName: SMSManager
 * @Description: 短信管理类
 * @author 杨瑜 45154139@qq.com
 * @date 2013-10-23 下午10:35:17
 * 
 */
public class SMSManager {
	private DBHelp dbHelp;
	private Context mContext;
	/**
	 * 消息类型(MsgType)
	 */
	private static final int REGISTER = 0x01; // 注册消息 上行 终端开机时向服务器注册
	private static final int LOCATION = 0x02; // 位置消息 上行 向服务器汇报当前位置信息
	private static final int EMERGENCY = 0x03; // 紧急呼叫 上行 紧急情况下呼叫服务器
	private static final int APPLYFOR = 0x04; // 申请导航规划 上行 终端向服务器索要导航规划
	private static final int MSGPUSH = 0x81; // 信息推送 下行 向客户端推送定制的信息（目前只支持短消息）
	private static final int GPSPUSH = 0x82; // 下载导航规划 下行 向客户端下载导航规划信息
	private static final int PHONE_GPS_PUSH = 0x83;// 手机发送导航信息
	private static final int CHANGE_LOCAL_NUMBER = 0x8F;// 更改本机号码


	private TelephonyManager mTelephonyManager;

	public SMSManager(Context context) {
		dbHelp = new DBHelp(context);
		mContext = context;
		mTelephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
	}

	/**
	 * 说明:解析收到的短信 Author:陈伟斌 2012-12-25
	 * 
	 * @param pdus
	 * @return
	 */
	public List<SMS> dealSMSofReceiver(Object[] pdus) {

		List<SMS> list = new ArrayList<SMS>();
		SmsMessage[] msg = new SmsMessage[pdus.length];
		for (int i = 0; i < pdus.length; i++) {

			msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

		}
		SMS sms;
		StringBuffer buffer = new StringBuffer();

		if (msg != null && msg.length > 0) {
			sms = new SMS();
			Date date = new Date(msg[0].getTimestampMillis());// 获得短信发送时间
			sms.date = CommonUtils.date2Str(date, null);
			sms.phoneNumber = msg[0].getDisplayOriginatingAddress();
			// sms.smsbody = msg[0].getDisplayMessageBody();
			for (SmsMessage currMsg : msg) {

				buffer.append(currMsg.getDisplayMessageBody());
			}
			sms.smsbody = buffer.toString();
			list.add(sms);
		}
		return list;

	}

	public void addSMSList(List<SMS> list) {
		dbHelp.addSMSList(list);
	}

	/**
	 * @Title: addSMS
	 * @Description: 新增短信
	 * @param msg
	 * @date 2013-10-23 下午10:40:26
	 * @author 陈伟斌
	 */
	public void addSMS(SMS msg) {
		dbHelp.addSMS(msg);
		mContext.sendBroadcast(new Intent(
				Constants.CXBBroadcast.SMS_REFRESH_ACTION));
	}

	/**
	 * @Title: setSMSHasRead
	 * @Description: 将短信设置为已读
	 * @param id
	 * @date 2013-10-23 下午10:40:47
	 * @author 陈伟斌
	 */
	public void setSMSHasRead(int id) {

		dbHelp.setSMSHasRead(id);
	}

	/**
	 * 说明:取得短信列表 Author:陈伟斌 2012-12-25
	 * 
	 * @return
	 */
	public List<SMS> getAllSMS() {

		return dbHelp.getAllSMS();

	}

	/**
	 * 说明:删除指定短信 Author:陈伟斌 2012-12-25
	 * 
	 * @param id
	 */
	public void deleteSMSById(int id) {

		dbHelp.deleteSMSById(id);
	}

	/**
	 * 说明:删除所有短信 Author:陈伟斌 2012-12-25
	 */
	public void deleteAllSMS() {
		dbHelp.deleteAllSMS();
	}

	/**
	 * 说明:取得总共有多少条短信 Author:陈伟斌 2012-12-26
	 * 
	 * @return
	 */
	public int getSMSTotalCount() {

		return dbHelp.getSMSTotalCount();
	}

	/**
	 * 说明:取得下一条短信(如果没有下一条则返回null) Author:陈伟斌 2012-12-27
	 * 
	 * @param currentSMSId
	 * @return
	 */
	public SMS getNextSMS(int currentSMSId) {

		return dbHelp.getNextSMS(currentSMSId);
	}

	/**
	 * 说明:取得上一条短信(如果没有上一条则返回null) Author:陈伟斌 2012-12-27
	 * 
	 * @param currentSMSId
	 * @return
	 */
	public SMS getPreSMS(int currentSMSId) {
		return dbHelp.getPreSMS(currentSMSId);
	}

	/**
	 * 说明:取得总共有多少条未读短信 Author:陈伟斌 2012-12-26
	 * 
	 * @return
	 */
	public int getSMSUnReadCount() {
		int count = dbHelp.getSMSUnReadCount();
		if (count > 99) {// 最多显示99条
			count = 99;
		}
		return count;
	}

	/**
	 * 说明:分析短信内容 Author:陈伟斌 2012-11-24
	 * 
	 * @param message
	 * @param receiveTime
	 * @return
	 */
	public void analysisDataFromSms(String message) {
		int nMsgType = Integer.parseInt(message.substring(2, 4), 16);

		switch (nMsgType) {

		case GPSPUSH:// 0x82 // 下载导航规划 下行 向客户端下载导航规划信息

			analyseNaviMessage(message);
			break;
		case PHONE_GPS_PUSH:
			analyseNaviMessage(message);
			break;

		default:

			break;
		}
		// return bRet;
	}

	public void sendMessage(String phone, String content) {
		SmsManager smsManager = SmsManager.getDefault();
		smsManager.sendMultipartTextMessage(phone, null,
				smsManager.divideMessage(content), null, null);
	}

	/**
	 * 
	 * 解析导航信息 陈伟斌 2013-3-28
	 */
	private void analyseNaviMessage(String message) {
		String gpsinfo = message.substring(16);
		GpsDestinationInfo gpsInfo = new GpsDestinationInfo();
		// ….. 填充结构
		gpsInfo.isEncrypt = true;

		String begin = gpsinfo;// 跳到E或者W
		int nWarpDirection = (begin.charAt(0) == 'W') ? -1 : 1;
		begin = begin.substring(1);// 跳过E或者W

		if (begin.indexOf(',') > 0)// 等于零也停止解析是因为,以下第二句要求大于零
		{
			gpsInfo.longitude = nWarpDirection
					* Double.valueOf(begin.substring(0, begin.indexOf(',')));
			begin = begin.substring(begin.indexOf(',') + 1);

			int nBroadwise = (begin.charAt(0) == 'S') ? -1 : 1;
			begin = begin.substring(1);// 跳过S或者N

			if (begin.indexOf(',') > 0)// 等于零也停止解析是因为,以下第二句要求大于零
			{
				gpsInfo.latitude = nBroadwise
						* Double.valueOf(begin.substring(0, begin.indexOf(',')));
				gpsInfo.destName = begin.substring(begin.indexOf(',') + 1);

			}

			CxbEventBus.getCxbBus(CxbEventBus.EVENT_RECEIVER_NAVIGATION).post(
					gpsInfo);

		} else {
			Log.e("SMSManager", " 数据有错,未分析出经度 消息类型:");
		}
	}


}
